<!-- 开盘批次弹窗 -->
<template>
  <div>
    <!-- 编辑弹窗 -->
    <Modal v-model="modal" :title="title" footer-hide width="800" :styles="{top: '20px'}">
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="150">
        <Row :gutter="16">
          <Col span="14">
          <FormItem label="批次名称：" prop="batchName">
            <Input type="text" v-model="formValidate.batchName" :disabled='isdisabled'
              maxlength="20"></Input>
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="24">
          <FormItem label="证件类型：" prop="certType">
            <Radio-group v-model="formValidate.certType">
              <Radio label="1" :disabled='isdisabled'>预售许可证</Radio>
              <Radio label="2" :disabled='isdisabled'>出售许可证</Radio>
            </Radio-group>
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="16" v-if="formValidate.certType==1">
          <Col span="14">
          <FormItem label="首次开盘时间：" prop="firstOpenTime">
            <DatePicker type="date" :disabled='isdisabled'
              v-model="formValidate.firstOpenTime"></DatePicker>
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="24">
          <FormItem label="许可证编号：" prop="certCode">
            <Input type="text" :disabled='isdisabled' v-model="formValidate.certCode"
              maxlength="50"></Input>
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="24" class="dingwei">
          <div class="ivu-form-item ivu-form-item-required">
            <FormItem label="许可证附件：" prop="imageVOS">
              <upload-file :maxNum=10 @handleSuccess="uploadSampleRoomImg"
                ref='uploadSampleRoom'></upload-file>
            </FormItem>
          </div>
          </Col>
        </Row>
        <Row :gutter="16" class="top_warp">
          <Col span='6' offset="2" class="total_num">关联产品/楼栋</Col>
          <Col span="3" offset="12" class="cityList_moudle_footer">
          <Button type="primary" @click="addProdectOrBuildModal" v-if="!isdisabled"
            style="margin-bottom:10px">添加</Button>
          </Col>
        </Row>
        <Table class="relation_table" :height="300" :columns="columnsProdect"
          :data="formValidate.bindBuildings">
        </Table>
        <Row :gutter="16">
          <Col span="6" offset="18" class="cityList_moudle_footer">
          <Button type="primary" @click="saveTableDatail('formValidate')"
            v-if="!isdisabled">保存</Button>
          <Button class="moudle_cancelButton" @click="modal = false">关闭</Button>
          </Col>
        </Row>
      </Form>
    </Modal>

    <!-- 添加关联产品和楼栋 -->
    <Modal v-model="modalAdd" title="新增产品/楼栋" footer-hide width="700">
      <Form ref="formValidateAdd" :model="formValidateAdd" :rules="ruleValidateAdd"
        :label-width="150">
        <Row :gutter="16">
          <Col span="14">
          <FormItem label="关联产品：" prop="AddProductId">
            <Select v-model="formValidateAdd.AddProductId" :label-in-value='true'
              placeholder="请选择" class="cityConfigArea_moudle_select"
              @on-change="changeAddProductName">
              <Option v-for="item in AddProductNameAttrSort" :key="item.productId"
                :value="item.productId">{{item.productName}}</Option>
            </Select>
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="16" v-if="formValidateAdd.AddProductId">
          <Col span="24">
          <FormItem label="关联楼栋：" prop="AddbuildName">
            <Checkbox :value="checkAll" @click.prevent.native="toggleAll"
              v-if="checkBuildArr.length>0">全选</Checkbox>
            <div>
              <Checkbox v-model="item.isSelected"
                @on-change="e=>{checkAllGroupChange(e,checkBuildArr)}"
                v-for="(item,index) in checkBuildArr" :key="index" :disabled="item.isdisabled">
                {{item.buildingName}}
              </Checkbox>
            </div>
          </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="6" offset="18" class="cityList_moudle_footer">
          <Button class="moudle_cancelButton" @click="modalAdd = false">取消</Button>
          <Button type="primary" @click="addProdectOrBuild('formValidateAdd')">确定</Button>
          </Col>
        </Row>
      </Form>
    </Modal>
  </div>
</template>

<script>
  import buildingApi from '@/biz/buildingManagement/openingBatch'
  import uploadFile from './uploadFile.vue'
  import columnsAll from '../columns/openingBatchColumns'
  export default {
    components: { uploadFile },
    data() {
      return {
        modal: false,
        title: '',
        formValidate: {
          batchName: '', //批次名称
          certType: '1', //证件类型
          firstOpenTime: null, //开盘时间
          certCode: '', //许可证编号
          imageVOS: [], //许可证附件
          bindBuildings: [], //关联产品和楼栋数组
        },
        ruleValidate: columnsAll.rule(),
        isdisabled: false, //控制是否可编辑
        columnsProdect: [],

        // 添加关联产品和楼栋
        modalAdd: false,
        AddProductNameAttrSort: [],
        formValidateAdd: {
          AddProductName: '',
          AddProductId: null,
          AddbuildName: [],
        },
        ruleValidateAdd: {
          AddProductId: [{ required: true, message: '请选择关联产品' }],
          AddbuildName: [],
        },
        indeterminate: false,
        checkAll: false,
        checkBuildArr: [], //关联楼栋数组数据
        targetList: [],
        batchId: '',
      }
    },
    props: {
      housesId: {
        type: Number,
        default: null,
      },
    },
    computed: {
      // 选择的源记录数量
      selectSourceItemNumber() {
        return this.checkBuildArr.filter((item) => item.bindStatus != 3).length
      },
    },
    watch: {},
    methods: {
      //查看 编辑 新建
      editChannel(data, type) {
        this.$refs.formValidate.resetFields()
        this.modal = true
        if (type == 'check') {
          this.title = '查看'
          this.isdisabled = true
          this.batchId = data.batchId
          this.getBatchDetailInfo(data.batchId)
        } else if (type == 'edit') {
          this.title = '编辑'
          this.isdisabled = false
          this.isNew = false
          this.batchId = data.batchId
          this.getBatchDetailInfo(data.batchId)
        } else {
          this.title = '新增'
          this.isNew = true
          this.isdisabled = false
          this.$refs['uploadSampleRoom'].fileList = []
          this.$refs['uploadSampleRoom'].init('')
          this.formValidate = {
            batchName: '', //批次名称
            certType: '1', //证件类型
            firstOpenTime: null, //开盘时间
            certCode: '', //许可证编号
            imageVOS: [], //许可证附件
            bindBuildings: [], //关联产品和楼栋数组
          }
        }
        console.log(data, type)
      },
      getBatchDetailInfo(batchId) {
        this.$refs['uploadSampleRoom'].fileList = []
        this.$refs['uploadSampleRoom'].init('')
        buildingApi.getBatchDetail({ batchId }).then((res) => {
          this.formValidate = Object.assign({}, this.formValidate, res)
          this.$refs['uploadSampleRoom'].fileList = res.file
        })
      },
      /*
       *  ===== 弹窗操作 ====
       */
      // 上传许可证附件
      uploadSampleRoomImg(e) {
        console.log('上传许可证附件', e)
        let arr = e
        this.formValidate.imageVOS = []
        arr.forEach((item) => {
          let params = {
            imageURL: item.url,
            imageId: item.name,
          }
          this.formValidate.imageVOS.push(params)
        })
        if (this.isdisabled) {
          this.updateimageVOS()
        }
      },
      //查看 更新许可证附件
      updateimageVOS() {
        let params = {
          imageVOS: this.formValidate.imageVOS,
          batchId: this.batchId
        }
        buildingApi.updateBatchAttach(params).then(res => {
          console.log(res)
          this.$Message.success('附件更新成功！')
        })
      },
      //删除关联产品/楼栋
      delProdectOrBuild(mess, isCheck) {
        console.log(mess, isCheck, 'delProdectOrBuild')
        let that = this
        if (!isCheck) {
          let index = mess._index
          this.formValidate.bindBuildings.splice(index, 1)
          console.log(this.formValidate.bindBuildings)
        } else {
          this.$Modal.confirm({
            title: '确认删除',
            content: `确认删除该关联产品/楼栋？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              let params = {
                buildingId: mess.buildingId,
              }
              buildingApi.cancelBatchBind(params).then((res) => {
                that.$Message.success('删除成功！')
                that.getBatchDetailInfo(that.batchId)
                that.$emit('saveTableBtn')
              }).catch(err => {
                that.$Message.error(err.msg)
              })
            },
          })
        }
      },
      //保存
      saveTableDatail() {
        this.$refs.formValidate.validate((valid) => {
          if (valid) {
            console.log(this.formValidate, 'formValidate')
            this.formValidate.housesId = this.housesId
            if (this.formValidate.certType != 1) {
              this.formValidate.firstOpenTime = ''
            }
            buildingApi.batchSaveOrEdit(this.formValidate).then((res) => {
              this.$Message.success('修改成功')
              this.modal = false
              this.$emit('saveTableBtn')
            })
          }
        })
      },
      //添加关联产品/楼栋
      addProdectOrBuildModal() {
        console.log('添加关联产品/楼栋')
        this.checkAll = false
        this.modalAdd = true
        this.getProductList()
      },
      //获取指定地块所有产品
      getProductList() {
        let params = {
          housesId: this.housesId,
        }
        buildingApi.housesGetDetail(params).then((res) => {
          this.$refs.formValidateAdd.resetFields()
          this.AddProductNameAttrSort = res.productDetails ?
            res.productDetails : []
        })
      },
      //切换关联产品
      changeAddProductName(obj) {
        console.log(obj)
        this.checkAll = false
        if (obj) {
          this.formValidateAdd.AddProductName = obj.label
          this.getBuildingList(obj.value)
        }
      },
      //获取指定产品所有楼栋
      getBuildingList(productId) {
        let params = {
          productId: productId,
          batchId: this.batchId,
          isNew: this.isNew,
        }
        console.log(params)
        buildingApi.proBuildingList(params).then((res) => {
          this.checkBuildArr = res
          this.checkBuildArr.map((item) => {
            item.productName = this.formValidateAdd.AddProductName
            if (item.bindStatus == 3) {
              item.isdisabled = true
              item.isSelected = false
            } else {
              if (item.bindStatus == 2) {
                item.isSelected = true
                item.isdisabled = true
              } else {
                item.isSelected = false
              }
            }
          })
        })
      },
      //全选、反选
      toggleAll() {
        console.log(this.checkAll, '11111111111')
        if (!this.checkAll) {
          this.checkAll = true
          this.checkBuildArr.map((item) => {
            if (!item.isSelected && item.bindStatus == 1) {
              item.isSelected = true
              this.checkAll = true
            }
          })
        } else {
          this.checkAll = false
          this.checkBuildArr.map((item) => {
            if (item.bindStatus == 1) {
              item.isSelected = false
            }
          })
        }
      },
      //chenck 改变
      checkAllGroupChange(e, data) {
        let len = this.checkBuildArr.filter((item) => item.isSelected).length
        let addlen = this.selectSourceItemNumber
        if (len == addlen) {
          this.checkAll = true
        } else if (data.length > 0) {
          this.checkAll = false
        } else {
          this.checkAll = false
        }
      },
      clearDuplicate(arr1, arr2) {
        for (var i = 0; i < arr2.length; i++) {
          for (var j = 0; j < arr1.length; j++) {
            if (arr2[i].buildingId == arr1[j].buildingId) {
              arr1.splice(j, 1)
            }
          }
        }
        return (arr2 = arr2.concat(arr1))
      },
      //新增产品、楼栋确定
      addProdectOrBuild() {
        this.formValidateAdd.AddbuildName = this.checkBuildArr.filter(
          (item) => item.isSelected
        )
        this.$refs.formValidateAdd.validate((valid) => {
          if (valid) {
            this.formValidate.bindBuildings = this.clearDuplicate(
              this.formValidateAdd.AddbuildName,
              this.formValidate.bindBuildings
            )
            this.checkBuildArr = []
            this.formValidateAdd.AddProductName = []
            this.modalAdd = false
          }
        })
      },
    },
    mounted() {
      this.columnsProdect = columnsAll.ModalColumns(this)
    },
  }
</script>
<style lang='scss' scoped>
  .cityList_moudle_footer {
    display: flex;
    justify-content: space-around;
    margin-top: 16px;
  }
</style>